import re

from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer

from django.contrib.auth.hashers import check_password, make_password
from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users import constants
from users.models import User, Address


class UserSerializers(serializers.ModelSerializer):
    """用户序列化器类"""
    # 非模型类的在外面定义
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id','username','password','mobile','password2','sms_code','allow','token')

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 是否同意协议,手机号格式,手机号是否存在,两次密码是否一致,短信验证码是否正确
    def validate_username(self, value):
        # 用户名不能全部为数字
        if re.match('^\d+$', value):
            raise serializers.ValidationError('用户名不能全部为数字')

        return value

    def validate_allow(self, value):
        # 是否同意协议
        if value != 'true':
            raise serializers.ValidationError('请同意验证')

        return value

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        # 手机号是否存在
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已存在')

        return value

    def validate(self, attrs):
        # 判断两次密码是否一直
        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        mobile = attrs['mobile']

        # 短信验证码是否正确
        redis_conn = get_redis_connection('verify_codes')

        # 取出短信验证码
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        # 判断是够过期
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码失效')

        # 对比验证码内容
        sms_code = attrs['sms_code'] # str

        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        """
        validated_data: 校验之后的数据
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 创建新用户
        user = User.objects.create_user(**validated_data)

        # 由服务器生成一个jwt token, 保存用户信息
        from rest_framework_jwt.settings import api_settings

        # 生成payload方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成载荷
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        # 给user对象增加属性token,保存jwt token的数据
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """用户序列化器类"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email','email_active')


class EmailSerializer(serializers.ModelSerializer):
    """邮箱设置序列化器类"""
    class Meta:
        model = User
        fields = ('id','email')

        extra_kwargs = {
            'email':{
                'required':True
            }
        }


    def update(self, instance, validated_data):
        # 1.设置登陆用户的邮箱
        email = validated_data['email']
        instance.email = email
        instance.save()

        # TODO:发送用户验证邮件
        # itsdangerous: 用来加密用户id
        # 验证链接: http://www.meiduo.site:8080/success_verify_email.html?user_id=<用户id>
        # 如果直接将用户的id放在验证链接中,可能会发生恶意请求
        # 将用户的信息进行加密,然后把加密之后的内容放在验证链接中
        # http://www.meiduo.site:8080/success_verify_email.html?token<加密用户的信息>
        verify_url = instance.generate_verify_email_url()

        # 发出发送邮件的任务消息
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        return instance


class AddressSerializer(serializers.ModelSerializer):
    """地址序列化器类"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        # 创建并保存新增地址数据

        # 获取登录用户对象
        user = self.context['request'].user
        validated_data['user'] = user

        # 调用ModelSerializer中create方法
        addr = super().create(validated_data)
        return addr


class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id','title',)


class BrowseHisorySerializer(serializers.Serializer):
    """历史浏览序列化器类"""
    sku_id = serializers.IntegerField(label='商品STU编号')

    def validate_sku_id(self, value):
        # sku_id是否存在
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        """redis中存储登录用户浏览的记录"""
        # 获取redis链接对象
        redis_conn = get_redis_connection('histories')

        user = self.context['request'].user

        # 拼接key
        history_key = 'history_%s' % user.id

        # 去重：如果商品已经被浏览,将id移除list
        stu_id = validated_data['sku_id']
        redis_conn.lrem(history_key, 0, stu_id)

        # 保持有序：商品id添加到到list最左侧
        redis_conn.lpush(history_key, stu_id)

        # 截取：保留最新的浏览商品id
        redis_conn.ltrim(history_key,0,constants.USER_BROWSING_HISTORY_COUNTS_LIMIT -1)

        return validated_data


class ChangPasswordSerializer(serializers.ModelSerializer):
    password = serializers.CharField(label='确认密码', write_only=True)
    password2 = serializers.CharField(label='确认密码', write_only=True)
    old_password = serializers.CharField(label='确认密码', write_only=True)

    class Meta:
        model = User
        fields = ('id','password','password2','old_password')

        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
            'password2': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
            }

    def validate(self, attrs):
        # print(type(attrs))
        # 判断两次密码是否一直
        password = attrs['password']
        password2 = attrs['password2']
        old_password = attrs['old_password']
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        # 判断旧密码是否正确
        user = self.context['request'].user
        if not check_password(old_password,user.password):
            raise serializers.ValidationError('原始密码错误')

        return attrs


    def create(self, validated_data):
        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['old_password']

        # 更新并保存密码
        user = self.context['request'].user
        password = make_password(validated_data['password'])
        user.password = password
        user.save()
        return user


class ForgetPasswordSerializer(serializers.Serializer):
    text = serializers.CharField(label='验证码')
    image_code_id = serializers.CharField(label='uuid值')
    username = serializers.CharField(label='用户名')
    mobile = serializers.CharField(label='手机号')
    access_token = serializers.CharField(label='token')


    class Meta:
        model = User
        fields = ('username','text','image_code_id','mobile','access_token')


    def validate(self, attrs):
        text = attrs['text']
        username = attrs['username']
        image_code_id = attrs['image_code_id']

        # 1.获取参数,判断用户是否存在
        if re.match('^1[3-9]\d{9}$', username):
            # 帐号为手机号
            user = User.objects.get(mobile=username)
        else:
            # 帐号为用户名
            user = User.objects.get(username=username)

        if not user:
            raise serializers.ValidationError('用户不存在')

        # 1.获取redis链接
        redis_conn = get_redis_connection('imagecode')

        # 判断验证码是否正确
        redis_image_code = redis_conn.get('image_code:%s' % image_code_id)
        if redis_image_code.decode().lower() != text:
            raise serializers.ValidationError('验证码错误')


        # 3.加密手机号
        list = user.mobile[3:7]
        newphone = user.mobile.replace(list, '****')

        # 4.加密用户token
        # TJWSSerializer(秘钥, 有效期秒)
        serialize = TJWSSerializer(secret_key=settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)

        user_info = {
            "id": user.id,
            "mobile": user.mobile
        }

        # 对用户信息进行加密
        token = serialize.dumps(user_info).decode()  # bytes->str


        attrs["mobile"] = newphone
        attrs["access_token"] = token
        # print(attrs)
        # 5.返回响应,手机号和状态

        return attrs
















